package com.azxcrm.project.system.user.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azxcrm.common.utils.DateUtils;
import com.azxcrm.common.utils.security.ShiroUtils;
import com.azxcrm.framework.config.AzxcrmConfig;
import com.azxcrm.framework.redis.template.service.RedisServiceImpl;
import com.azxcrm.framework.web.controller.BaseController;
import com.azxcrm.project.monitor.workflow.common.CommonService;
import com.azxcrm.project.monitor.workflow.domain.WorkFlowApply;
import com.azxcrm.project.monitor.workflow.service.WorkFlowApplyService;
import com.azxcrm.project.system.basic.domain.OrderDispatch;
import com.azxcrm.project.system.basic.service.IOrderDispatchService;
import com.azxcrm.project.system.customer.domain.CustomerClue;
import com.azxcrm.project.system.customer.domain.CustomerInfo;
import com.azxcrm.project.system.customer.service.ICustomerClueService;
import com.azxcrm.project.system.customer.service.ICustomerInfoService;
import com.azxcrm.project.system.dept.domain.Dept;
import com.azxcrm.project.system.dept.service.IDeptService;
import com.azxcrm.project.system.menu.domain.Menu;
import com.azxcrm.project.system.menu.service.IMenuService;
import com.azxcrm.project.system.order.domain.Order;
import com.azxcrm.project.system.order.domain.OrderVisitRecord;
import com.azxcrm.project.system.order.service.IOrderDealService;
import com.azxcrm.project.system.order.service.IOrderService;
import com.azxcrm.project.system.order.service.IOrderVisitRecordService;
import com.azxcrm.project.system.user.domain.User;

/**
 * 首页 业务处理
 * 
 * @author Dustyone
 */
@Controller
public class IndexController extends BaseController
{
    @Autowired
    private IMenuService menuService;

    @Autowired
    private AzxcrmConfig azxcrmConfig;
    
    @Autowired
    private IOrderService orderService; 
    
	@Autowired
	private IOrderDispatchService orderDispatchService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private ICustomerInfoService customerInfoService;
	
	@Autowired
	private ICustomerClueService customerClueService;
	
	/**
	 * Redis服务
	 */
	@Autowired
	private RedisServiceImpl redisServiceImpl;
	
	@Autowired
	private WorkFlowApplyService workFlowApplyService;
	
	@Autowired
	private IOrderDealService orderDealService;
	
	@Autowired
	private IOrderVisitRecordService orderVisitRecordService;
	
	@Autowired
	private IDeptService deptService;
	
	
	/**
	 * 派单员角色
	 */
	@Value("${crm.role.dispatcher}")
	private String dispatcher;

	/**
	 * 派单员主管
	 */
	@Value("${crm.role.dispatcherManager}")
	private String dispatcherManager;
	
	/**
	 * 部门经理角色Key
	 */
	@Value("${crm.role.departmentManager}")
	private String departmentManager;

    // 系统首页
    @GetMapping("/index")
    public String index(Order order, Model model) throws ParseException
    {
        // 取身份信息
        User user = getUser();
        // 根据用户id取出菜单
        List<Menu> menus = menuService.selectMenusByUserId(user.getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("user", user);
        model.addAttribute("copyrightYear", azxcrmConfig.getCopyrightYear());
        return "index";
    }
    
 // Wap系统首页
	@GetMapping("/indexWap")
    public String indexWap(Order order, Model model) throws ParseException
    {
    	 // 取身份信息
        User user = getUser();
        model.addAttribute("user", user);
      
        //获取待跟进订单信息
   		OrderDispatch orderDispatch = new OrderDispatch();
   		order.setSalesUserId(ShiroUtils.getUserId().intValue());
   		orderDispatch.setOrder(order);
   		//派单员角色
   		model.addAttribute("dispatcher", ShiroUtils.hasRole(dispatcher));
   		//派单员主管角色
   		model.addAttribute("dispatcherManager", ShiroUtils.hasRole(dispatcherManager));
   		//获取待跟进订单条数
   		Integer orderCount = orderService.selectOrderCount(user.getDeptId().intValue());
   		model.addAttribute("orderCount", orderCount); 
   		//待审批事项
   		if(ShiroUtils.hasRole(departmentManager)) {
   			List<Order> orders = new ArrayList<>();
   			ArrayList<String> businessKeys = new ArrayList<>();
   			String businessKey = "";
   			List<Task> list = commonService.findTaskByUserId(String.valueOf(ShiroUtils.getUserId()));
   			for (Task task : list) {
   				ProcessInstance result = runtimeService.createProcessInstanceQuery()
   						.processInstanceId(task.getProcessInstanceId()).singleResult();
   				// 获得业务流程的bussinessKey
   				businessKey = result.getBusinessKey();
   				businessKeys.add(businessKey);
   				WorkFlowApply flowInfo = workFlowApplyService.selectWorkFlowApplyByBusinessId(businessKey);
   				if (flowInfo.getOrderId() != null) {
					//将TaskId保存在Redis中:K-orderId:V-taskId
					redisServiceImpl.set(flowInfo.getOrderId().toString(), task.getId());
					redisServiceImpl.expire(flowInfo.getOrderId().toString(), 60); //设置缓存过期时间
				}
   			}
   			if(list.size()==0 || list.get(0)==null || list==null) {
   				model.addAttribute("examine", 1);
   			}else {
			//查询订单IDs
			Integer[] orderIdListIds = workFlowApplyService.selectWorkFlowApplyByBusinessIds(businessKeys);
			order.setOrderIds(orderIdListIds);
			//查询订单信息
			order.setOrderType(1);
			order.setAuditStatus(1);
			order.setAuditType(2);
			order.setOrderStatus(3);
			order.setDeptId(ShiroUtils.getUser().getDeptId().intValue());
			orders = orderService.selectOrderAuditList(order);
			if(orders != null && orders.size()>0){
				for(Order orderInfo : orders){
					//将缓存中的taskId填充到订单数据中
					orderInfo.setTaskId(redisServiceImpl.get(orderInfo.getOrderId().toString()).toString());
				}
			}
			model.addAttribute("examine", orders);
		}
   		}else {
   			model.addAttribute("examine", 1);
   		}
   		
   		//查询跟进中列表信息
   		List<OrderDispatch> dispatchList = orderDispatchService.wapOrderDispatchList(orderDispatch);
   		List<OrderDispatch> orderDispatchList = new ArrayList<OrderDispatch>();
   		for (OrderDispatch od : dispatchList) {
   			Long dateNum = DateUtils.getDaySub(DateUtils.getDate(), od.getProtectTime());
   			od.setDateNum(dateNum);
   			orderDispatchList.add(od);
   			if(dateNum<0) {
   				order.setOrderStatus(0);
   				}
   		}
   		model.addAttribute("orderDispatchList", orderDispatchList);
  	     
    	return "indexWap";
    }

    // 系统介绍
    @GetMapping("/system/main")
    public String main(Model model)
    {
    	//总客户数
    	List<CustomerInfo> customerInfo = customerInfoService.selectCustomerInfoList(new CustomerInfo());
    	model.addAttribute("customerInfoSize", customerInfo.size());
    	
    	//总成交金额
    	double money = orderDealService.SumProductPrice();
    	model.addAttribute("money", money);
    	
    	//客户线索总数
    	int clueCount = customerClueService.customerSumCount();
    	model.addAttribute("clueCount", clueCount);
    	
    	//线上客户线索总数
    	List<CustomerClue> upperclue = customerClueService.selectCustomerClueList(new CustomerClue());
    	model.addAttribute("upperclueSize", upperclue.size());
    	
    	//线下客户线索总数
    	CustomerClue customerClue = new CustomerClue();
    	customerClue.setClueSource(4);
    	List<CustomerClue> lowerclue = customerClueService.selectCustomerClueList(customerClue);
    	model.addAttribute("lowerclueSize", lowerclue.size());
    	
    	//待回访统计数
    	OrderVisitRecord orderVisitRecord = new OrderVisitRecord();
    	orderVisitRecord.setVisitStatus(1);
    	List<OrderVisitRecord> ovr = orderVisitRecordService.selectOrderVisitRecordList(orderVisitRecord);
    	model.addAttribute("ovrSize", ovr.size());
    	
    	//订单统计
    	List<Order> tourismr = orderService.selectStatusCount(13);//统计乐享旅游
    	model.addAttribute("tourismr", tourismr);
    	List<Order> recure = orderService.selectStatusCount(14);//统计康复项目
    	model.addAttribute("recure", recure);
    	List<Order> department = orderService.selectStatusCount(15);//统计二期床位
    	model.addAttribute("department", department);
    	List<Order> sum = orderService.selectSumStatusCount();//订单统计总合
    	model.addAttribute("sum", sum);
    	
        model.addAttribute("version", azxcrmConfig.getVersion());
        return "main";
    }
    
    /**
     * 统计乐享旅游数据接口
     */
    @GetMapping("/system/censusTourismr")
    @ResponseBody
    public List<Order> censusTourismr(){
    	List<Order> tourismr = orderService.selectStatusCount(13);//统计乐享旅游
    	return tourismr;
    }
    
    /**
     * 统计康复项目数据接口
     */
    @GetMapping("/system/censusRecure")
    @ResponseBody
    public List<Order> censusRecure(){
    	List<Order> recure = orderService.selectStatusCount(14);//统计康复项目
    	return recure;
    }
    
    /**
     * 统计二期床位数据接口
     */
    @GetMapping("/system/censusDepartment")
    @ResponseBody
    public List<Order> censusDepartment(){
    	List<Order> department = orderService.selectStatusCount(15);//统计二期床位
    	return department;
    }
    
    /**
     * 各部门销售订单金额统计
     */
    @GetMapping("/system/censusDeptProductPrice")
    @ResponseBody
    public List<Dept> censusDeptProductPrice(String startTime,String endTime){
    	List<Dept> deptProductPrice = deptService.censusDeptproductPrice(startTime,endTime);//统计二期床位
    	return deptProductPrice;
    }

}
